#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Time    : 21-3-24 上午11:28
# @Author  : zgd
# @Site    : 
# @File    : views.py
# @Software: PyCharm
from flask import current_app
from flask import g
from flask import jsonify
from flask import redirect
from flask import render_template
from flask import request

from info import constants
from info import db
from info.models import News, Category
from info.utils.commons import user_login_data
from info.utils.response_code import RET
from . import profile_blue
from info.utils.image_storage import image_stroage





# 请求路径: /user/user_follow
# 请求方式: GET
# 请求参数:p
# 返回值: 渲染user_follow.html页面,字典data数据
# 获取我的关注
# 请求路径: /user/user_follow
# 请求方式: GET
# 请求参数:p
# 返回值: 渲染user_follow.html页面,字典data数据
@profile_blue.route('/user_follow')
@user_login_data
def user_follow():
    """
    1. 获取参数,p
    2. 参数类型转换
    3. 分页查询收藏的新闻
    4. 获取分页对象属性,总页数,当前页,当前页对象列表
    5. 将对象列表,转成字典列表
    6. 拼接数据,渲染页面
    :return:
    """
    # 1. 获取参数,p
    page = request.args.get("p","1")

    # 2. 参数类型转换
    try:
        page = int(page)
    except Exception as e:
        page = 1

    # 3. 分页查询用户关注的作者
    try:
        paginate = g.user.followed.paginate(page,2,False)
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.DBERR,errmsg="获取作者失败")

    # 4. 获取分页对象属性,总页数,当前页,当前页对象列表
    totalPage = paginate.pages
    currentPage = paginate.page
    items = paginate.items

    # 5. 将对象列表,转成字典列表
    author_list = []
    for author in items:
        author_list.append(author.to_dict())

    # 6. 拼接数据,渲染页面
    data = {
        "totalPage":totalPage,
        "currentPage":currentPage,
        "author_list":author_list
    }
    return render_template("news/user_follow.html",data=data)



# @profile_blue.route('/user_follow')
# @user_login_data
# def user_follow():
#
#     page = request.args.get("p","1")
#
#     try:
#          page = int(1)
#     except:
#         page = 1
#
#     #用户关注的作者
#     try:
#         paginate = g.user.followed.paginate(page, 4, False)
#     except Exception as e:
#         current_app.logger.error(e)
#         return jsonify(errno=RET.DBERR ,errmsg="查询用户关注失败")
#
#
#     totalPage = paginate.pages
#     currentPage = paginate.page
#     items = paginate.items
#
#     author_list = []
#     for author in items:
#         author_list.append(author.to_dict())
#
#     data = {
#         "totalPage":totalPage,
#         "currentPage":currentPage,
#         "author_list":author_list
#         }
#
#     return render_template("news/user_follow.html",data=data)
#


# 新闻列表
# 请求路径: / user / news_list
# 请求方式: GET
# 请求参数: p
# 返回值: GET渲染user_news_list.html页面
#
@profile_blue.route('/news_list')
@user_login_data
def news_list():

    # 拿到页码数
    page = request.args.get("p","1")
    try:
        page = int(page)
    except:
        page = 1

    try:
        # paginate = News.query.filter(News.user_id == g.user.id).order_by(News.create_time.desc()).paginate(page,3,False)
        paginate = News.query.filter(News.user_id == g.user.id).order_by(News.create_time.desc()).paginate(page,3,False)

    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.DBERR ,errmsg="查询新闻失败")

    totalPage = paginate.pages
    currentPage = paginate.page
    items = paginate.items

    news_lists = []
    for news in items:
        news_lists.append(news.to_review_dict())

    data = {
        "totalPage":totalPage,
        "currentPage":currentPage,
        "news_list":news_lists
    }

    return render_template("/news/user_news_list.html",data=data)
#
#     """
#      1. 获取参数,p
#      2. 参数类型转换
#      3. 分页查询收藏的新闻
#      4. 获取分页对象属性,总页数,当前页,当前页对象列表
#      5. 将对象列表,转成字典列表
#      6. 拼接数据,渲染页面
#      :return:
#      """
#     # 1. 获取参数,p
#     page = request.args.get("p", "1")
#
#     # 2. 参数类型转换
#     try:
#         page = int(page)
#     except Exception as e:
#         page = 1
#
#     # 3. 分页查询用户发布的新闻
#     try:
#         paginate = News.query.filter(News.user_id == g.user.id).order_by(News.create_time.desc()).paginate(page, 3,
#                                                                                                            False)
#     except Exception as e:
#         current_app.logger.error(e)
#         return jsonify(errno=RET.DBERR, errmsg="获取新闻失败")
#
#     # 4. 获取分页对象属性,总页数,当前页,当前页对象列表
#     totalPage = paginate.pages
#     currentPage = paginate.page
#     items = paginate.items
#
#     # 5. 将对象列表,转成字典列表
#     news_list = []
#     for news in items:
#         news_list.append(news.to_review_dict())
#
#     # 6. 拼接数据,渲染页面
#     data = {
#         "totalPage": totalPage,
#         "currentPage": currentPage,
#         "news_list": news_list
#     }
#     return render_template("news/user_news_list.html", data=data)

# 请求路径: /user/news_release
# 请求方式:GET,POST
# 请求参数:GET无, POST ,title, category_id,digest,index_image,content
# 返回值:GET请求,user_news_release.html, data分类列表字段数据, POST,errno,errmsg
@profile_blue.route('/news_release', methods=['GET', 'POST'])
@user_login_data
def news_release():
    # 判断请求方式
    # get获取到　分类数据，渲染页面
    if request.method == "GET":
        try:
            #查询所有分类
            categories = Category.query.all()
        except Exception as e:
            current_app.logger.error(e)
            return jsonify(errno=RET.DBERR ,errmsg="查询分类失败")
        category_list = []
        for category in categories:
            category_list.append(category.to_dict())

        #渲染页面
        return render_template("/news/user_news_release.html",categories=category_list)

    # post获取参数
    title = request.form.get("title")
    category_id = request.form.get("category_id")
    digest = request.form.get("digest")
    index_image = request.files.get("index_image")
    content = request.form.get("content")
    # 校验参数 为空校验
    if not all([title,category_id,digest,index_image,content]):
        return jsonify(errno=RET.PARAMERR,errmsg="参数不全")

    # 上传图片
    try:
        image_name = image_stroage(index_image)
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.THIRDERR ,errmsg="七牛云异常，上传图片失败")

    # 判断image_name是否为空
    if not image_name:
        return jsonify(errno=RET.DATAERR ,errmsg="图片上传失败")

    # 创建新闻对象设置新闻属性
    news = News()
    news.title = title
    news.source = g.user.nick_name
    news.digest = digest
    news.content = content
    news.index_image_url = constants.QINIU_DOMIN_PREFIX + image_name
    news.category_id = category_id
    news.user_id = g.user.id
    news.status = 1 #审核中

    # 保存到数据库
    try:
        db.session.add(news)
        db.session.commit()
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.DATAERR ,errmsg="新闻发布失败")

    #返回响应
    return jsonify(errno=RET.OK ,errmsg="发布成功")



# 获取新闻收藏列表
# 请求路径: /user/ collection
# 请求方式:GET
# 请求参数:p(页数)
# 返回值: user_collection.html页面
@profile_blue.route('/collection')
@user_login_data
def collection():
    """
    1. 获取参数,p
    2. 参数类型转换
    3. 分页查询收藏的新闻
    4. 获取分页对象属性,总页数,当前页,当前页对象列表
    5. 将对象列表,转成字典列表
    6. 拼接数据,渲染页面
    :return:
    """

    # 1.获取参数, p
    page = request.args.get("p",1)

    # 2.参数类型转换
    try:
        page = int(page)
    except Exception as e:
        page = 1

    try:
        # 3.分页查询收藏的新闻
        paginate = g.user.collection_news.order_by(News.create_time.desc()).paginate(page,3,False)
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.DBERR ,errmsg="获取新闻失败")

    # 4.获取分页对象属性, 总页数, 当前页, 当前页对象列表
    totalPage =paginate.pages
    currentPage = paginate.pages
    items = paginate.items

    # 5.将对象列表, 转成字典列表
    news_list = []
    for news in items:
        news_list.append(news.to_dict())

    data = {
        "totalPage":totalPage,
       "currentPage":currentPage,
        "news_list":news_list
    }

    return render_template("news/user_collection.html",data=data)



# 修改密码
#　路径/user/pass_info
#　方式get  post
#　请求参数　无，　POST有参数　new_password　　new_password2
#　返回值　GET

@profile_blue.route('/pass_info', methods=['GET', 'POST'])
@user_login_data
def pass_info():
    #如果是get　就展示页面
    if request.method =="GET":
        return render_template("news/user_pass_info.html")

    #请求方式是 post
    old_password = request.json.get("old_password")
    new_password = request.json.get("new_password")
    new_password2 = request.json.get("new_password2")


    # 拿到参数    校验参数

    if not all([old_password,new_password,old_password]):
        return jsonify(errno=RET.PARAMERR ,errmsg="数据为不全")

    if not g.user.check_password(old_password):
        return jsonify(errno=RET.DATAERR ,errmsg="老密码错误")

    #设置新密码
    g.user.password = new_password

    #返回响应
    return jsonify(errno=RET.OK ,errmsg="设置密码成功")



# 请求路径: /user/pic_info
# 请求方式:GET,POST
# 请求参数:无, POST有参数,avatar
# 返回值:GET请求: user_pci_info.html页面,data字典数据, POST请求: errno, errmsg,avatar_url
@profile_blue.route('/pic_info', methods=['GET', 'POST'])
@user_login_data
def pic_info():
    if request.method =="GET":
        return render_template("news/user_pic_info.html",user_info=g.user.to_dict())


    # 获取文件参数,
    avatar = request.files.get("avatar")

    # 检验参数
    if not avatar:
        return jsonify(errno=RET.DATAERR ,errmsg="图片不能为空")

    # 读取图片为二进制，上传头像
    try:
        image_name = image_stroage(avatar.read())
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.THIRDERR ,errmsg="上传头像失败")

    #如果没有图片，则上传失败
    if not image_name:
        return jsonify(errno=RET.NODATA ,errmsg="图片上传失败")

    # 设置头像
    g.user.avatar_url = image_name

    #返回响应
    data = {
        "avatar_url":constants.QINIU_DOMIN_PREFIX + image_name
    }
    return jsonify(errno=RET.OK ,errmsg="上传成功",data=data)



# 请求路径: /user/base_info
# 请求方式:GET,POST
# 请求参数:POST请求有参数,nick_name,signature,gender
# 返回值:errno,errmsg
# 用户基本信息
@profile_blue.route('/base_info', methods=['GET', 'POST'])
@user_login_data
def base_info():
    """
    # get 获取用户信息
    # post　修改用户信息
    # 获取参数
    # 检验参数
    # 为空校验
    # 修改信息保存数据库
    # 返回响应
    """

    # get 获取用户信息
    if request.method=="GET":
        return render_template("news/user_base_info.html",user_info=g.user.to_dict())


    # post　修改用户信息
    # 获取参数
    nick_name = request.json.get("nick_name")
    signature = request.json.get("signature")
    gender = request.json.get("gender")

    # 检验参数
    # 为空校验
    if not all([nick_name,gender,signature]):
        return jsonify(errno=RET.PARAMERR, errmsg="缺少数据")
    if not gender in ["MAN","WOMAN"]:
        return jsonify(errno=RET.DATAERR ,errmsg="性别设置错误")

    # 修改信息保存数据库
    g.user.signature = signature
    g.user.gender = gender
    g.user.nick_name = nick_name

    # 返回响应
    return jsonify(errno=RET.OK ,errmsg="修改成功")

@profile_blue.route('/user_index')
@user_login_data
def user_index():
    if not g.user:
        return redirect("/")

    data = {
        "user_info":g.user.to_dict()

        }
    return render_template("news/user.html",data=data)



























